package com.project_test.kun.travelling_1st.HomePage.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.project_test.kun.travelling_1st.GoodsDetailActivities.CarDetail.CarDetailActivity;
import com.project_test.kun.travelling_1st.HomePage.Util.URL;
import com.project_test.kun.travelling_1st.HomePage.adapter.HomePCarListAdapter;
import com.project_test.kun.travelling_1st.HomePage.category.HomePCarListItem;
import com.project_test.kun.travelling_1st.HomePage.category.HomePCarType;
import com.project_test.kun.travelling_1st.HomePage.category.HomePCarTypeListItem;
import com.project_test.kun.travelling_1st.R;
import com.project_test.kun.travelling_1st.beans.GlobalCity;
import com.project_test.kun.travelling_1st.toolActivity.CityChooseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomePageCarActivity extends AppCompatActivity implements View.OnClickListener {
    private int pirceOrderType=-1;//价格排序标志，-1是低价，1是高价
    private String priceOrderString=URL.CAR_MIN;
    private RequestQueue mRequestQueue;
    private TextView mCityText;
    private ImageView mExit;
    private RadioGroup mCarGroup;
    private LinearLayout mBtnLine;
    private HomePCarType mCarType;
    private List<HomePCarTypeListItem> mTypeListItems;
    private List<HomePCarListItem> mListItems;
    private HomePCarListAdapter mListadapter;
    private PullToRefreshListView mListView;
    private int type=0;
    private String Cityname="北京";
    private int city_id=143;//默认北京
    private  int pager=1;//页数
    private boolean level=true;//点击了那个按钮
    private ListView mDropList;
    private List<Map<String,String>> mMaps;
    private SimpleAdapter mDropAdapter;
    private boolean dropState=true;
    private String priceLabel;
    private RadioButton homepage_Car_price;
    //
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page_car);
//       getSupportActionBar().hide();
        mRequestQueue = Volley.newRequestQueue(this);
        //初始化数据信息
        mCarType=new HomePCarType();
        mListItems=new ArrayList<>();
        mTypeListItems=new ArrayList<>();
        mMaps=new ArrayList<>();
        initView();
        initData(URL.HOMEPAGER_CAR_DEFAULT);//加载默认的数据
        initTypeInfo(URL.HOMEPAGER_CAR_TYPE);//加载车辆类型
    }
    private  Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                ((RadioButton)mCarGroup.getChildAt(0)).setText(mCarType.getTitle());
                for (int i = 0; i < mTypeListItems.size(); i++) {
                    Map<String,String> map=new HashMap<>();
                    HomePCarTypeListItem typeListItem = mTypeListItems.get(i);
                    map.put("title",typeListItem.getTitle());
                    mMaps.add(map);
                }
                mDropAdapter.notifyDataSetChanged();
            }
            if (msg.what==1){
                dropState=true;
                mDropList.setVisibility(View.GONE);
                String url=URL.HOMEPAGER_CAR_COMMONT+URL.CAR_TYPE_ID+type+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+URL.CAR_MIN+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                mListItems.clear();
                initData(url);

            }
            if (msg.what==999){
                mListView.onRefreshComplete();
            }
        }
    };
    private void initTypeInfo(String url) {
        JsonObjectRequest tabRequest=new JsonObjectRequest(Request.Method.GET,url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONObject data = response.getJSONObject("data");
                            mCarType.pashJsonObject(data);
                            mTypeListItems.addAll(mCarType.getHomePCarTypeListItems());
                            Message msg = mHandler.obtainMessage();
                            msg.what=0;
                            mHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        mRequestQueue.add(tabRequest);
    }


    private void initData(String url) {
        //获取listView中的数据
       JsonObjectRequest listRequest=new JsonObjectRequest(Request.Method.GET,url, null,
               new Response.Listener<JSONObject>() {
                   @Override
                   public void onResponse(JSONObject response) {
                       try {
                           JSONArray data = response.getJSONArray("data");
                           for (int i = 0; i < data.length(); i++) {
                               HomePCarListItem listItem=new HomePCarListItem();
                               listItem.pashJsonObject(data.getJSONObject(i));
                               mListItems.add(listItem);
                           }
                          mListadapter.notifyDataSetChanged();
                           Message message = mHandler.obtainMessage();
                           message.what=999;
                           mHandler.sendMessage(message);
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                   }
               },
               new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {

           }
       });
        mRequestQueue.add(listRequest);

    }

    private void initView() {
        homepage_Car_price= (RadioButton) findViewById(R.id.homepage_Car_price);
        mCityText = (TextView) findViewById(R.id.homepage_Car_cityText);
        mCityText.setText(Cityname);
        mExit = (ImageView) findViewById(R.id.exit);
        mCarGroup = (RadioGroup) findViewById(R.id.homepager_Car_Rdio);
        mBtnLine = (LinearLayout) findViewById(R.id.homepage_Car_btnLine);
        mDropList = (ListView) findViewById(R.id.homepage_Car_dropdownList);
        mDropAdapter = new SimpleAdapter(HomePageCarActivity.this,mMaps, R.layout.item_activity_homep_droplist,
                new String[]{"title"},new int[]{R.id.item_droptext_list_homep});
        mDropList.setAdapter(mDropAdapter);
        ((RadioButton)mCarGroup.getChildAt(0)).setChecked(true);//默认选中第一个
        mListView = (PullToRefreshListView) findViewById(R.id.homepage_Car_PlistView);
        //设置刷新模式
        mListView.setMode(PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
        mListadapter = new HomePCarListAdapter(HomePageCarActivity.this,mListItems);
        mListView.setAdapter(mListadapter);
       //对控件设置点击监听
        setListener();
    }

    private void setListener() {
        mExit.setOnClickListener(this);
        mCityText.setOnClickListener(this);
        final View btnLine0 = mBtnLine.getChildAt(0);
        ((RadioButton)mCarGroup.getChildAt(0)).setOnClickListener(this);
        mDropList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HomePCarTypeListItem typeListItem = mTypeListItems.get(i);
                type=typeListItem.getId();
                Message message = mHandler.obtainMessage();
                message.what=1;
                mHandler.sendMessage(message);
            }
        });
        final View btnLine1 = mBtnLine.getChildAt(1);
        mCarGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                switch (i) {

                    case R.id.homepage_Car_carType:
                        pager=1;
                        level=true;
                        btnLine0.setBackgroundColor(getResources().getColor(R.color.text_pressed_green));
                        btnLine1.setBackgroundColor(getResources().getColor(R.color.colorWhite));

                        mListItems.clear();
                        if (type==0){//初始数据
                            String url=URL.HOMEPAGER_CAR_COMMONT+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                            initData(url);
                        }else{
                            String url=URL.HOMEPAGER_CAR_COMMONT+URL.CAR_TYPE_ID+type+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                            initData(url);
                        }

                        break;
                    case R.id.homepage_Car_price:
                        pager=1;
                        level=false;
                        dropState=false;//点击后默认隐藏
                        btnLine0.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                        btnLine1.setBackgroundColor(getResources().getColor(R.color.text_pressed_green));
                        mListItems.clear();
                        switch (pirceOrderType) {
                            case -1:
                                priceOrderString=URL.CAR_MIN;
                                priceLabel="价格最低";
                                break;
                            case 1:
                                priceOrderString=URL.CAR_MAX;
                                priceLabel="价格最高";
                                break;
                        }
                        if (type==0){//初始数据
                            String url=URL.HOMEPAGER_CAR_COMMONT+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+ priceOrderString+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                            initData(url);
                        }else{
                            String url=URL.HOMEPAGER_CAR_COMMONT+URL.CAR_TYPE_ID+type+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+ priceOrderString+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                            initData(url);
                        }
                        pirceOrderType*=-1;
                        homepage_Car_price.setText(priceLabel);
                        break;
                }
            }
        });
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pager=pager+1;
                if (pager>5){//防止多次加载程序崩溃
                    Message message = mHandler.obtainMessage();
                    message.what=999;
                    mHandler.sendMessage(message);
                    return;
                }
                if(type==0){//默认状态
                    if (level){
                        String url=URL.HOMEPAGER_CAR_COMMONT+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                        initData(url);
                    }else{
                        String url=URL.HOMEPAGER_CAR_COMMONT+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+priceOrderString+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                        initData(url);
                    }
                }else{//选完车型后
                if (level){
                    String url=URL.HOMEPAGER_CAR_COMMONT+URL.CAR_TYPE_ID+type+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                    initData(url);
                }else {
                    String url=URL.HOMEPAGER_CAR_COMMONT+URL.CAR_TYPE_ID+type+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+priceOrderString+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
                    initData(url);
                }
                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.exit:
                HomePageCarActivity.this.finish();//关闭activity
                break;
            case R.id.homepage_Car_cityText:
                Intent intent=new Intent(HomePageCarActivity.this, CityChooseActivity.class);
                startActivity(intent);


                break;
            case R.id.homepage_Car_carType:


                if (dropState){
                    mDropList.setVisibility(View.VISIBLE);
                }else{
                    mDropList.setVisibility(View.GONE);
                }

                dropState=!dropState;
                break;
        }

    }




    @Override
    protected void onResume() {
        super.onResume();
        mCityText.setText(GlobalCity.getInstance().getGlobalCityName());
        mListItems.clear();
        String url=URL.HOMEPAGER_CAR_COMMONT+URL.HOMEPAGER_CAR_CITY_ID+GlobalCity.getInstance().getGlobalCityId()+ priceOrderString+URL.CAR_PAGE+pager+URL.HOMEPAGER_CAR_LASTCOMMONT;
        initData(url);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int vid=mListItems.get(position).getId();
                String vvid=vid+"";
                Intent intent=new Intent(HomePageCarActivity.this,CarDetailActivity.class);
                intent.putExtra("vid",vvid);
                startActivity(intent);
            }
        });

    }
}
